package com.android.launcher3.views;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.launcher3.R;
import com.android.launcher3.Utilities;
import com.android.launcher3.widget.AudioWidget;
import com.android.launcher3.widget.DateWidget;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.x.compoent.gnss.GnssCompoent;
import com.x.compoent.gnss.GnssTool;
import com.x.component.hardware.ProcStatsData;
import com.x.component.hardware.SocComponent;

import java.text.DecimalFormat;
import java.util.Arrays;

///负一屏
public class FirstScreen1 extends FrameLayout {

    private DonutProgress mCleanUpProgress;

    private final static int CLEANUP_ANIMATION_DURATION = 3000;

    private final Handler handler = new Handler();

    public FirstScreen1(@NonNull Context context) {
        super(context);
        init();
    }

    public FirstScreen1(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public FirstScreen1(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private View layoutContainer;
    private TextView tv_cpuInfo;
    private View vCpuIcon;
    private View layoutStatus;
    private TextView tv_ram;
    private TextView tv_gps;
    private TextView tv_rom;
    private TextView tv_clean_up;

    private ProgressBar progress1;
    private ProgressBar progress2;
    private ProgressBar progress3;
    private ProgressBar progress4;
    private ProgressBar progress5;
    private ProgressBar progress6;
    private ProgressBar progress7;
    private ProgressBar progress8;

    private DonutProgress donutProgress;
    private DonutProgress donut_ram;
    private DonutProgress donut_rom;
    private DonutProgress donut_gnss;

    private RelativeLayout layoutRam;
    private RelativeLayout layoutRom;
    private RelativeLayout layoutGps;
    private RelativeLayout layoutCleanup;
    private FrameLayout layoutDonutProgress;
    private LinearLayout layoutProgressbar;

    private ProgressBar[] progressBarArrays = null;

    private DateWidget dateWidget;

    private AudioWidget audio;
    private View audioGap;


    void init() {
        LayoutInflater.from(getContext()).inflate(R.layout.first_screen1, this, true);
        layoutContainer = findViewById(R.id.layout_container);
        tv_cpuInfo = findViewById(R.id.tv_cpuInfo);
        tv_gps = findViewById(R.id.tv_gps);
        vCpuIcon = findViewById(R.id.v_cpu_icon);
        layoutStatus = findViewById(R.id.layout_status);
        tv_ram = findViewById(R.id.tv_ram);
        tv_rom = findViewById(R.id.tv_rom);
        tv_clean_up = findViewById(R.id.tv_clean_up);

        progress1 = findViewById(R.id.progress1);
        progress2 = findViewById(R.id.progress2);
        progress3 = findViewById(R.id.progress3);
        progress4 = findViewById(R.id.progress4);
        progress5 = findViewById(R.id.progress5);
        progress6 = findViewById(R.id.progress6);
        progress7 = findViewById(R.id.progress7);
        progress8 = findViewById(R.id.progress8);

        layoutRam = findViewById(R.id.layout_ram);
        layoutRom = findViewById(R.id.layout_rom);
        layoutGps = findViewById(R.id.layout_gps);
        layoutCleanup = findViewById(R.id.layout_cleanup);
        layoutDonutProgress = findViewById(R.id.layout_donut_progress);
        layoutProgressbar = findViewById(R.id.layout_progressbar);

        donutProgress = findViewById(R.id.donut_progress);
        donut_ram = findViewById(R.id.donut_ram);
        donut_rom = findViewById(R.id.donut_rom);
        donut_gnss = findViewById(R.id.donut_gnss);

        progressBarArrays = new ProgressBar[8];
        progressBarArrays[0] = progress1;
        progressBarArrays[1] = progress2;
        progressBarArrays[2] = progress3;
        progressBarArrays[3] = progress4;
        progressBarArrays[4] = progress5;
        progressBarArrays[5] = progress6;
        progressBarArrays[6] = progress7;
        progressBarArrays[7] = progress8;

        layoutCleanup.setOnClickListener(v -> cleanUp());
        mCleanUpProgress = findViewById(R.id.p_cleanup);

        audio = findViewById(R.id.audio);
        audioGap = findViewById(R.id.audio_gap);
        dateWidget = findViewById(R.id.date_widget);

        screenAdaption();

        Log.d("TinkerCPU", "here we go");
        try {
            DecimalFormat frequencyFormat = new DecimalFormat("#.0");

            SocComponent INSTANCE = SocComponent.getInstance();
            INSTANCE.init(getContext());
            int availableProcessors = INSTANCE.availableProcessors();
            String maxCpuFrequency = INSTANCE.readMaxCpuFrequency();
            float[] temperatures = INSTANCE.getCPUTemperatures(getContext(), availableProcessors);
            double totalTemperatures = 0;
            double averageTemperatures = 0;
            if (temperatures != null) {
                for (int i = 0; i < temperatures.length; i++) {
                    progressBarArrays[i].setProgress((int) temperatures[i]);
                    totalTemperatures += temperatures[i];
                }
            }
            averageTemperatures = totalTemperatures / availableProcessors;
            donutProgress.setProgress((int) averageTemperatures);
            String formattedAvg = frequencyFormat.format(averageTemperatures);

            donutProgress.setText(formattedAvg + " °c ");

            ProcStatsData.MemInfo meminfo = INSTANCE.getCpuRamInfo();
            double realTotalRam = meminfo.realTotalRam;
            double realFreeRam = meminfo.realFreeRam;
            double realUsedRam = meminfo.realUsedRam;

            ProcStatsData.RomInfo rominfo = INSTANCE.getDeviceRomInfo();
            long realUsedRom = rominfo.realUsedRom;
            long realFreeRom = rominfo.realFreeRom;
            long realTotalRom = rominfo.realTotalRom;

            final double bytesPerGB = 1024 * 1024 * 1024;

            int frequency = Integer.parseInt(maxCpuFrequency);
            //         2400000
            double dFreq = (double) frequency / 1000000;

            String formatFreq = frequencyFormat.format(dFreq);
            StringBuffer sb = new StringBuffer();
            sb.append(availableProcessors);
            sb.append(" Core ");
            sb.append(formatFreq);
            sb.append(" GHz");

            tv_cpuInfo.setText(sb.toString());

            // 将字节数转换为GB
            int totalRam = (int) Math.round((realTotalRam / bytesPerGB));
            float freeRam = (float) (realFreeRam / bytesPerGB);
            int usedRam = (int) Math.round((realUsedRam / bytesPerGB));
            int ramProgress = (int) ((freeRam * 100) / totalRam);
            donut_ram.setProgress(ramProgress);

            int totalRom = Integer.parseInt(rominfo.totalRom);
            int freeRom = Integer.parseInt(rominfo.freeRom);

            int romProgress = (int) ((freeRom * 100) / totalRom);
            donut_rom.setProgress(romProgress);

            DecimalFormat decimalFormat = new DecimalFormat("#.0");
            String formattedNumber = decimalFormat.format(freeRam);

            String formattedNumberFreeRom = decimalFormat.format(freeRom);

            tv_ram.setText(meminfo.uiFreeRam + " / " + meminfo.uiTotalRam + " GB");
            Log.d("TinkerCPU", "availableProcessors " + availableProcessors);
            Log.d("TinkerCPU", "maxCpuFrequency " + maxCpuFrequency);
            Log.d("TinkerCPU", "temperatures " + Arrays.toString(temperatures));

            Log.d("TinkerCPU", "realTotalRam " + realTotalRam);
            Log.d("TinkerCPU", "realFreeRam " + realFreeRam);
            Log.d("TinkerCPU", "realUsedRam " + realUsedRam);


            tv_rom.setText(rominfo.freeRom + " / " + rominfo.totalRom + " GB");

            GnssCompoent.getInstance().init(getContext());
            GnssCompoent.getInstance().setGnssTool(new GnssTool() {
                @Override
                public void onGnssSignalStrengthChanged(int level) {
                    tv_gps.setText(String.valueOf(level));
                    donut_gnss.setProgress(level);
                }

                @Override
                public void onLocationChanged(Location location) {
                    float speed = location.getSpeed(); // 速度，单位：m/s
                    float speedKmh = speed * 3.6f; // 转换为km/h
                    Log.d("TinkerGnss", "Speed: " + speedKmh + " km/h");
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {

                }

                @Override
                public void onProviderEnabled(String provider) {

                }

                @Override
                public void onProviderDisabled(String provider) {

                }
            });

        } catch (Throwable e) {
            e.printStackTrace();
            Log.d("TinkerCPU", "Exception " + e.getMessage());
        }

        try {
            int cacheSize = (int) SocComponent.getInstance().getCacheFileSize();
            tv_clean_up.setText(cacheSize + " M");
        } catch (Exception e) {
        }
    }

    private void cleanUp() {

        ///开动画
        startAnimation(0);


    }

    private void startAnimation(int time) {

        if (time >= CLEANUP_ANIMATION_DURATION) {
            mCleanUpProgress.setProgress(0);
            onCleanUpAnimationFinish();
            return;
        }

        int progress = time / 10;

        if (progress > 100) {
            progress = progress - 100;
        }

        mCleanUpProgress.setProgress(progress);

        handler.postDelayed(() -> startAnimation(time + 10), 10);

    }

    private void onCleanUpAnimationFinish() {
        //刷新UI显示
        int randomNumber = (int) (Math.random() * 10);
        tv_clean_up.setText(randomNumber + " M");
    }


    void screenAdaption() {

        boolean isStripScreen = Utilities.isLongStripScreen(getContext());

        View cpuName = findViewById(R.id.layout_cpu_name);
        View cpuStatus = findViewById(R.id.layout_cpu_status);

        post(() -> {
            ViewGroup.LayoutParams layoutParams = cpuName.getLayoutParams();
            layoutParams.width = cpuStatus.getWidth();
            cpuName.setLayoutParams(layoutParams);

        });

        if (isStripScreen) {

            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

            cpuName.setPadding(Utilities.pxFromDp(10, displayMetrics), Utilities.pxFromDp(2, displayMetrics), Utilities.pxFromDp(10, displayMetrics), Utilities.pxFromDp(2, displayMetrics));

            LinearLayout.LayoutParams cpuIconLayoutParamslayoutParams = (LinearLayout.LayoutParams) vCpuIcon.getLayoutParams();

            cpuIconLayoutParamslayoutParams.width = Utilities.pxFromDp(20, displayMetrics);
            cpuIconLayoutParamslayoutParams.height = Utilities.pxFromDp(22, displayMetrics);
            vCpuIcon.setLayoutParams(cpuIconLayoutParamslayoutParams);


            RelativeLayout.LayoutParams layoutStatusLayoutParams = (RelativeLayout.LayoutParams) layoutStatus.getLayoutParams();
            layoutStatusLayoutParams.height = Utilities.pxFromDp(110, displayMetrics);
            layoutStatus.setLayoutParams(layoutStatusLayoutParams);

            layoutRam.setPadding(0, Utilities.pxFromDp(5, displayMetrics), 0, Utilities.pxFromDp(5, displayMetrics));
            layoutRom.setPadding(0, Utilities.pxFromDp(5, displayMetrics), 0, Utilities.pxFromDp(5, displayMetrics));
            layoutGps.setPadding(0, Utilities.pxFromDp(5, displayMetrics), 0, Utilities.pxFromDp(5, displayMetrics));
            layoutCleanup.setPadding(0, Utilities.pxFromDp(5, displayMetrics), 0, Utilities.pxFromDp(5, displayMetrics));

            RelativeLayout.LayoutParams layoutDonutProgressLayoutParams = (RelativeLayout.LayoutParams) layoutDonutProgress.getLayoutParams();
            layoutDonutProgressLayoutParams.height = Utilities.pxFromDp(60, displayMetrics);
            layoutDonutProgressLayoutParams.width = Utilities.pxFromDp(60, displayMetrics);
            layoutDonutProgress.setLayoutParams(layoutDonutProgressLayoutParams);

            RelativeLayout.LayoutParams layoutProgressbarLayoutParams = (RelativeLayout.LayoutParams) layoutProgressbar.getLayoutParams();
            layoutProgressbarLayoutParams.height = Utilities.pxFromDp(55, displayMetrics);
            layoutProgressbar.setLayoutParams(layoutProgressbarLayoutParams);

            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) dateWidget.getLayoutParams();
            layoutParams.setMargins(layoutParams.leftMargin, Utilities.pxFromDp(5, displayMetrics), layoutParams.rightMargin, layoutParams.bottomMargin);
            dateWidget.setLayoutParams(layoutParams);
            dateWidget.useAutoType();

            audio.setVisibility(VISIBLE);
            audioGap.setVisibility(VISIBLE);

            FrameLayout.LayoutParams layoutContainerLayoutParams = (FrameLayout.LayoutParams) layoutContainer.getLayoutParams();
            layoutContainerLayoutParams.setMargins(0, 0, 0, Utilities.pxFromDp(100, getResources().getDisplayMetrics()));
        }

        ///统一跳转圆圈进度条大小

        post(() -> {

//                    int donutProgressWidth = donutProgress.getWidth();
//                    int donutProgressHeight = donutProgress.getHeight();
//                    ViewGroup.LayoutParams donutProgressLayoutParams = donutProgress.getLayoutParams();
//                    donutProgressLayoutParams.width = (int) (Math.min(donutProgressWidth, donutProgressHeight) * 0.7);
//                    donutProgressLayoutParams.height = (int) (Math.min(donutProgressWidth, donutProgressHeight) * 0.7);
//                    donutProgress.setLayoutParams(donutProgressLayoutParams);

                    double scale = Utilities.isLongStripScreen(getContext()) ? 0.55 : 0.7;

                    int donut_ramProgressWidth = donut_ram.getWidth();
                    int donut_ramProgressHeight = donut_ram.getHeight();
                    ViewGroup.LayoutParams donut_ramProgressLayoutParams = donut_ram.getLayoutParams();
                    donut_ramProgressLayoutParams.width = (int) (Math.min(donut_ramProgressWidth, donut_ramProgressHeight) * scale);
                    donut_ramProgressLayoutParams.height = (int) (Math.min(donut_ramProgressWidth, donut_ramProgressHeight) * scale);
                    donut_ram.setLayoutParams(donut_ramProgressLayoutParams);


                    int donut_romProgressWidth = donut_rom.getWidth();
                    int donut_romProgressHeight = donut_rom.getHeight();
                    ViewGroup.LayoutParams donut_romProgressLayoutParams = donut_rom.getLayoutParams();
                    donut_romProgressLayoutParams.width = (int) (Math.min(donut_romProgressWidth, donut_romProgressHeight) * scale);
                    donut_romProgressLayoutParams.height = (int) (Math.min(donut_romProgressWidth, donut_romProgressHeight) * scale);
                    donut_rom.setLayoutParams(donut_romProgressLayoutParams);

                    int donut_gnssProgressWidth = donut_gnss.getWidth();
                    int donut_gnssProgressHeight = donut_gnss.getHeight();
                    ViewGroup.LayoutParams donut_gnssProgressLayoutParams = donut_gnss.getLayoutParams();
                    donut_gnssProgressLayoutParams.width = (int) (Math.min(donut_gnssProgressWidth, donut_gnssProgressHeight) * scale);
                    donut_gnssProgressLayoutParams.height = (int) (Math.min(donut_gnssProgressWidth, donut_gnssProgressHeight) * scale);
                    donut_gnss.setLayoutParams(donut_gnssProgressLayoutParams);

                    int cleanUpProgressWidth = mCleanUpProgress.getWidth();
                    int cleanUpProgressHeight = mCleanUpProgress.getHeight();
                    ViewGroup.LayoutParams cleanUpProgressLayoutParams = mCleanUpProgress.getLayoutParams();
                    cleanUpProgressLayoutParams.width = (int) (Math.min(cleanUpProgressWidth, cleanUpProgressHeight) * scale);
                    cleanUpProgressLayoutParams.height = (int) (Math.min(cleanUpProgressWidth, cleanUpProgressHeight) * scale);
                    mCleanUpProgress.setLayoutParams(cleanUpProgressLayoutParams);

                }
        );


    }


}

